// 云函数入口文件
const cloud = require('wx-server-sdk')

//初始化云函数
cloud.init({
  env: 'test-csp1e'
})
// 1. 连接数据库
const db = cloud.database();
// 2. 获取集合
const stamp = db.collection('stamp');

// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID;

  // 1. 获取数据库的邮卡
  let result = await stamp.where({
    '_openid': openid
  }).get()
  cards = result.data[0].cards;
  for (let i = 0; i < cards.length; i++) {
    cards[i].number--;
  }
  let updatecards = await stamp.where({
    '_openid': openid
  }).update({
    data: {
      "cards": cards,
    }
  })
  return {
    updatecards,
  }
}